<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>{{ title }}</span>
    </div>
    <div>
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            placeholder="请选择"
            class="input1"
            v-model="formData.subjectID"
            @change="change"
          >
            <el-option
              v-for="item in subjectIDlist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select
            placeholder="请选择"
            class="input1"
            v-model="formData.catalogID"
            @change="change0"
          >
            <el-option
              v-for="item in catalogIDlist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 下拉 -->
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select
            placeholder="请选择"
            class="input1"
            v-model="formData.enterpriseID"
          >
            <el-option
              v-for="item in enterpriseIDlist"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 两个下拉 -->
        <el-form-item label="城市:" prop="province">
          <el-select
            placeholder="请选择"
            class="city"
            v-model="formData.province"
            @change="change1"
          >
            <el-option
              v-for="(item, index) in provinceslist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            placeholder="请选择"
            class="input2 city"
            v-model="formData.city"
            ref="city"
          >
            <el-option
              v-for="(item, index) in cityslist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 下拉 -->
        <el-form-item label="方向:" prop="direction">
          <el-select
            placeholder="请选择"
            class="input1"
            v-model="formData.direction"
          >
            <el-option
              v-for="(item, index) in directionlist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 单选框 -->
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 单选框 -->
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 题干 富文本编辑器-->
        <el-form-item label="题干:" prop="question">
          <quill-editor
            v-model="formData.question"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 选项 单选框/多选框/简答框 -->
        <el-form-item
          label="选项:"
          v-if="formData.questionType === 1 || formData.questionType === 2"
        >
          <ul>
            <li
              style="list-style-type: none"
              v-for="item in arry"
              :key="item.code"
              class="li"
            >
              <el-row>
                <el-col :span="1" v-if="formData.questionType === 1">
                  <div>
                    <!-- 单选 -->
                    <el-radio :label="item" v-model="radio" @change="clickradio"
                      >{{ item.code }}:</el-radio
                    >
                  </div>
                </el-col>
                <el-col :span="1" v-else-if="formData.questionType === 2">
                  <div>
                    <!-- 多选 -->
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox :label="item" name="type"
                        >{{ item.code }}:</el-checkbox
                      >
                    </el-checkbox-group>
                  </div>
                </el-col>
                <el-col :span="1">
                  <div>
                    <!-- 输入框 -->
                    <el-input
                      class="input3"
                      v-model="item.title"
                      @change="inputchange"
                    ></el-input>
                  </div>
                </el-col>
                <el-col :span="1">
                  <div>
                    <!-- 图片上传 -->
                    <el-upload
                      class="upload avatar-uploader"
                      action="#"
                      list-type="picture-card"
                      :limit="limit"
                      :show-file-list="false"
                      :on-success="
                        (res, file, fileList) => onSuccess(res, index)
                      "
                      :before-upload="beforeAvatarUpload"
                      :http-request="upload"
                    >
                      <span> 上传图片 </span>
                      <i
                        class="el-icon-circle-close crossicon"
                        index="100000"
                      ></i>
                    </el-upload>
                  </div>
                </el-col>
              </el-row>
            </li>
          </ul>

          <el-button
            type="danger"
            :disabled="formData.questionType === 1 ? true : false"
            ref="addOptionsBtn"
            class="dangerbtn"
            @click="addOptionsBtn"
          >
            <span> +增加选项与答案 </span>
          </el-button>
        </el-form-item>
        <!-- 解析视频输入框 -->
        <el-form-item label="解析视频:">
          <el-input class="input1" v-model="formData.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析富文本编辑器 -->
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            v-model="formData.answer"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注文本框 -->
        <el-form-item label="题目备注:">
          <el-input
            type="textarea"
            class="input1"
            v-model="formData.remarks"
          ></el-input>
        </el-form-item>
        <!-- 试题标签下拉-->
        <el-form-item label="试题标签:">
          <el-select
            placeholder="请选择试题标签"
            class="input1"
            v-model="formData.tags"
            multiple
          >
            <el-option
              v-for="(item, index) in tagslist"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            style="float: left; padding: 10px 20px"
            :type="type"
            size="medium"
            @click="confirm"
            >{{ confirms }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { simple as catalog } from '@/api/hmmm/directorys.js'
import { list as enterprise } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as tags } from '@/api/hmmm/tags.js'
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
import hljs from 'highlight.js'
import { add, update, detail } from '@/api/hmmm/questions.js'

const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDgCSSCfrlPmMgjW2HFxOYQ1MPCjzyg7HB', // 身份识别ID
  SecretKey: 'f3B2cvxiCOJyMULwGJ5aolUx94i5B07y' // 身份秘钥
})
export default {
  data () {
    return {
      formData: {
        // subjectID: '', // 学科
        // catalogID: '', // 目录
        // enterpriseID: '', // 企业
        // province: '', // 城市
        // city: '', // 地区
        // direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        // question: '', // 题干
        options: [
          // {
          //   isRight: false,
          //   code: '', // 代码
          //   title: '', // 标题
          //   img: '' // 图片URL
          // }
        ]
        // 选项
        // videoURL: '', // 解析视频
        // answer: '', // 答案解析
        // remarks: '', // 题目备注
        // tags: '', // 试题标签
        // isPerfect: '' // 是否精选题
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur,change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur,change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur,change' }],
        province: [{ required: true, message: '请选择地区', trigger: 'change,blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur,change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur,change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur,change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      },
      checkList: [],
      checked: true,
      subjectIDlist: [], // 学科列表
      catalogIDlist: [], // 目录列表
      enterpriseIDlist: [], // 企业列表
      provinceslist: [], // 城市列表
      cityslist: [], // 地区列表
      tagslist: [], // 标签列表
      directionlist: [], // 方向列表
      questionType: [], // 题型
      difficulty: [], // 难度
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }], // toggled buttons
            ['blockquote', 'code-block', 'image', 'link']
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      }, // 富文本编辑器设置
      arry: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ],
      limit: 1,
      title: '试题录入',
      type: 'primary',
      confirms: '确认提交',
      radio: null
    }
  },
  watch: {
    checkList (newValue, oldValue) {
      this.arry.map(i => {
        i.isRight = false
        newValue.map(n => {
          if (n.code === i.code) {
            i.isRight = true
          }
        })
      })
      // console.log(this.arry)
      this.formData.options = this.arry
    }
  },
  mounted () {
    this.getsubjectID()
    // this.getcatalogID()
    this.getenterpriseID()
    this.getcitys()
    this.getprovinces()
    this.getdirection()
    this.getJumpdata()
    this.radioisright()
  },
  methods: {
    confirm () {
      // 兜底校验
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            // 修改接口
            this.formData.questionType = String(this.formData.questionType)
            this.formData.difficulty = String(this.formData.difficulty)
            await update({ id: this.formData.id })
          } else {
            // 添加接口
            this.formData.questionType = String(this.formData.questionType)
            this.formData.difficulty = String(this.formData.difficulty)
            await add(this.formData)
          }
          this.$message.success(`${this.formData.id ? '修改' : '录入'}试题成功`)
          // this.$message.success('录入试题成功')
          this.$router.push('/questions/list')
          this.$refs.form.resetFields()
        }
      })
    },
    radioisright () {
      this.arry.map(i => {
        if (i.code === this.radio) {
          i.isRight = true
        }
      })
    },
    // 学科下拉框
    async getsubjectID () {
      const res = await simple()
      // console.log(res.data, '1')
      this.subjectIDlist = res.data
      // console.log(this.formData.subjectID, '2')
    },
    // 学科改变
    change (val) {
      // console.log(val)
      this.getcatalogID(val)
    },
    // 目录下拉框
    async getcatalogID (val) {
      const res = await catalog(val)
      // console.log(res, '3')
      this.catalogIDlist = res.data
    },
    // 企业下拉框
    async getenterpriseID () {
      const res = await enterprise()
      // console.log(res, '4')
      this.enterpriseIDlist = res.data.items
    },
    // 地区下拉框
    async getcitys (val) {
      const res = await citys(val)
      // console.log(res, '5')
      this.cityslist = res
      // console.log(this.cityslist)
    },
    // 城市下拉框
    async getprovinces () {
      const res = await provinces()
      // console.log(res, '6')
      this.provinceslist = res
    },
    // 城市改变
    change1 (val) {
      this.getcitys(val)
      // this.$refs
      // console.log(val, 'val')
    },
    change0 (val) {
      // console.log(val)
      this.gettags(val)
    },
    async gettags (val) {
      const res = await tags(val)
      // console.log(res)
      this.tagslist = res.data
      console.log(this.tagslist, '569')
      // console.log(this.arry, '6559')
    },
    getdirection () {
      this.directionlist = direction
      // console.log(this.directionlist)
      this.difficulty = difficulty
      this.questionType = questionType
    },
    // 添加选项事件
    addOptionsBtn () {
      const last = this.arry[this.arry.length - 1].code
      console.log(last)
      const conversion = last.charCodeAt() + 1
      const conversion2 = String.fromCharCode(conversion)
      this.arry.push({
        code: conversion2,
        title: '',
        img: '',
        isRight: false
      })
    },
    inputchange () {
      this.arry.map(item => {
        if (item.value) {
          this.formData.options.map(l => {
            l.title = item.value
          })
          // console.log(item.img, '11')
        }
      })
      // console.log(this.formData.options, '8')
    },

    // 修改试题
    async getJumpdata () {
      // console.log(this.$route.query.id, '666')
      if (this.$route.query.id) {
        const res = await detail(this.$route.query)
        this.formData = res.data
        this.formData.questionType = Number(this.formData.questionType)
        this.formData.difficulty = Number(this.formData.difficulty)
        const newArr = []
        res.data.options.map(i => {
          if (i.isRight === 1) {
            newArr.push(i)
          }
        })
        this.radio = newArr
        this.checkList = newArr
        this.arry = res.data.options
        // this.formData=res
        this.title = '试题修改'
        this.type = 'success'
        this.confirms = '确认修改'
      }
    },
    upload (res) {
      // console.log(res.file)
      // console.log(res, '100')
      if (res.file) {
        // 执行上传操作
        cos.putObject(
          {
            Bucket: 'img-1313016023' /* 存储桶 */,
            Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
            Key: res.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: res.file, // 上传文件对象
            onProgress: progressData => {
              console.log(JSON.stringify(progressData))
              // 图片上传的过程中不断执行的回调函数，这里可以做上传进度相关的功能
              // this.percent = progressData.percent * 100
            }
          },
          (err, data) => {
            console.log(err || data)
            // 上传成功和失败都会执行的函数
            // 上传成功之后
            if (data.statusCode === 200) {
              // this.formData.options.img = `https://${data.Location}`
              this.arry.map(i => {
                i.img = `https://${data.Location}`
              })
            }
          }
        )
      }
    },
    onSuccess (res, index) {
      const imgUrl = res.data
      console.log(imgUrl, '55555')
    },
    beforeAvatarUpload (file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    },
    clickradio (i) {
      // console.log(i, '55')
      this.formData.options.map(l => {
        l.code = i
        // console.log(this.formData.options, '99')
      })
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .ql-editor {
  height: 200px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
.el-radio {
  display: inline-block;
}
.input1 {
  width: 400px;
}
.city {
  width: 198px;
}
.input2 {
  margin: 0 0 0 5px;
}
.input3 {
  width: 240px;
  // margin-left: -24px;
}
/deep/.el-upload {
  margin-left: 205px;
  margin-top: -10px;
  width: 100px;
  height: 60px;
  span {
    position: relative;
    top: -44px;
    left: 9px;
  }
}
.option-css {
  width: 544px;
  height: 80px;
  padding-bottom: 20px;
}
.dangerbtn {
  position: relative;
  top: -6px;
  width: 123px;
  height: 32px;
}
.el-button {
  span {
    font-size: 12px;
    position: relative;
    top: -2px;
    left: -5px;
  }
}
.li {
  margin-bottom: 20px;
}
.crossicon {
  position: relative;
  top: -70px;
  left: 17px;
  // transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
</style>
